package models

import (
	"context"
	"database/sql"
	"fmt"
	"ginim/utils"
	"gorm.io/gorm"
	"time"
)

type User struct {
	gorm.Model
	Name          string `gorm:"column:name" json:"name"`
	Password      string `json:"password"`
	Phone         string `valid:"matches(^1[3-9]{1}\\d{9}$)" json:"phone"`
	Email         string `valid:"email" json:"email"`
	LoginTime     sql.NullTime
	HeartbeatTime sql.NullTime
	LogoutTime    sql.NullTime
	IsLogout      bool
	DeviceInfo    string
	ClientIP      string
	ClientPort    string
	Identity      string
	Salt          string
	Avatar        string `json:"avatar"`
}

func (t *User) TableName() string {
	return "user"
}

func FindUserByNameAndPassword(name string, password string) User {
	user := User{}
	utils.DB.Where("name = ? and password = ?", name, password).First(&user)
	return user
}

func FindUserByName(name string) User {
	user := User{}
	utils.DB.Where("name = ?", name).First(&user)
	return user
}

func FindUserById(id uint) User {
	user := User{}
	utils.DB.Where("id = ?", id).First(&user)
	return user
}

func FindUserByPhone(phone string) User {
	user := User{}
	utils.DB.Where("phone = ?", phone).First(&user)
	return user
}

func FindUserByEmail(email string) User {
	user := User{}
	utils.DB.Where("email = ?", email).First(&user)
	return user
}

func GetUserList() []*User {
	data := make([]*User, 10)
	utils.DB.Find(&data)
	return data
}

func CreateUser(user User) *gorm.DB {
	return utils.DB.Create(&user)
}

func DeleteUser(user User) *gorm.DB {
	return utils.DB.Delete(&user)
}

func UpdateUser(user User) *gorm.DB {
	return utils.DB.Model(&user).Updates(User{
		Name:     user.Name,
		Password: user.Password,
		Phone:    user.Phone,
		Email:    user.Email,
		Avatar:   user.Avatar,
	})
}

func UpdateUserIdentity(id uint) {
	user := User{}
	str := fmt.Sprintf("%d", time.Now().Unix())
	tmp := utils.MD5Decode(str)
	utils.DB.Model(&user).Where("id = ?", id).Update("identity", tmp)
}

func SetOnlineInfo(key string, val []byte, ttl time.Duration) {
	ctx := context.Background()
	utils.REDIS.Set(ctx, key, val, ttl)
}
